package com.turtle.security.security.service;

import com.turtle.security.common.exception.CustomException;
import com.turtle.security.security.dto.AuthUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录认证验证
 *
 * @author turtle
 * date: 2020-05-11
 */
@Component
@Slf4j
public class AuthService {

    @Resource
    private AuthenticationManager authenticationManager;


    /**
     * 账号密码登录验证
     *
     * @param username 登录账号
     * @param password 登录密码
     * @return AuthUserDTO 认证用户信息
     */
    public AuthUserDTO login(String username, String password) {
        Authentication authentication = null;
        try {
            // 这里会自动执行我们自定义的CustomerUserDetailsService类里的loadUserByUsername方法
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (BadCredentialsException badCredentialsException) {
            log.error(badCredentialsException.getMessage());
            throw new CustomException("账号或密码错误，请重新登录");
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new CustomException(e.getMessage());
        }

        return (AuthUserDTO) authentication.getPrincipal();

    }
}
